import sys
import time
from ConfigParser import SafeConfigParser
from subprocess import Popen, PIPE

import pkg_resources
from elementtree.SimpleXMLWriter import XMLWriter
import simplejson

from redarrow.dispatcher import run_command, Config

DEFAULT_CONFIG_FILE = '/etc/redarrow.conf'

def dispatch_commands(command, options, outfile=sys.stdout):
    config = Config(options.config_file)
    result = run_command(config, command)
    json_result = jsonize_result(result, pretty=options.pretty_print)
    print json_result

def prepare_option_parser(usage="%prog [options]"):
    from optparse import OptionParser
    parser = OptionParser(usage=usage,
            version=str(pkg_resources.get_distribution('RedArrow')))
    parser.add_option('-c', '--config-file', default=DEFAULT_CONFIG_FILE,
            help="Path to config file [default: %s]" % DEFAULT_CONFIG_FILE)
    return parser

def jsonize_result(result, pretty=False):
    result = result.copy()
    if 'start_time' in result:
        result['start_time'] = time.strftime("%Y-%m-%d %H:%M:%S",
                                             time.localtime(result['start_time']))
    return simplejson.dumps(result, indent=pretty and 4 or None)

def main():
    parser = prepare_option_parser(usage="%prog [options] command")
    parser.add_option('--pretty-print', action='store_true')
    options, args = parser.parse_args()

    if len(args) > 1:
        parser.error("Only one command supported, currently.")

    dispatch_commands(args[0], options)
